package com.ywgt.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.ywgt.handler.BusinessException;
import com.ywgt.response.Result;
import com.ywgt.response.ResultCode;
import com.ywgt.system.listener.WebUserListener;
import com.ywgt.system.mapper.UserMapper;
import com.ywgt.system.pojo.*;
import com.ywgt.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@Slf4j
@RestController
@Api(value = "文件管理" ,tags = "文件模块")
@RequestMapping("/system/file")
@CrossOrigin
public class FileController {

    @Autowired
    private FileService fileService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private InStockService inStockService;


    @PostMapping("/upload")
    @ApiOperation(value = "文件上传服务",notes = "文件上传")
    public Result upload(MultipartFile file){
        if (file.isEmpty()|| StringUtils.isEmpty(file.getOriginalFilename())){
         throw new BusinessException(ResultCode.PARAM_IS_BLANK.getResultCode(),ResultCode.PARAM_IS_BLANK.getResultMessage());
        }
        String url = fileService.upload(file);
        return Result.ok().data("url",url);
    }

    @PostMapping("/delete")
    @ApiOperation(value = "文件删除服务",notes = "文件删除")
    public Result delete(String file){
        if(!StringUtils.isEmpty(file)){
            System.out.println(file);
        }
        fileService.delete(file);
        return Result.ok();
    };

    @PostMapping("/downloadUserExcel")
    @ApiOperation(value = "用户信息Excel",notes = "下载用户Excel")
    @ResponseBody
    public void getUserExcel(HttpServletResponse response)  {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String filename= URLEncoder.encode("员工信息","UTF-8");
            response.setHeader("Content-Disposition","attachment;filename*=UTF-8''"+filename+".xls");
            EasyExcel.write(response.getOutputStream(),User.class).sheet("员工信息").doWrite(userService.list());
        } catch (IOException e) {
            log.error("下载Excel文件失败");
            e.printStackTrace();
        }
    }

    @PostMapping("/uploadUserExcel")
    @ApiOperation(value = "导入用户Excel",notes = "导入用户信息")
    public Result ReadExcel(MultipartFile file) {
        ExcelReader reader =null;
        try {
            //获取文件输入流
            InputStream inputStream = file.getInputStream();
            reader = EasyExcel.read(inputStream, User.class, new WebUserListener(userMapper)).build();
            ReadSheet sheet = EasyExcel.readSheet(0).build();
            reader.read(sheet);
            return Result.ok();
        } catch (IOException e) {
            log.error("导入Excel文件失败");
            e.printStackTrace();
            return Result.error();
        } finally {
            if (reader!=null){
                //这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
                reader.finish();
            }
        }
    }

    @PostMapping("/downloadMenuExcel")
    @ApiOperation(value = "菜单信息Excel",notes = "下载菜单Excel")
    @ResponseBody
    public void getMenuExcel(HttpServletResponse response)  {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String filename= URLEncoder.encode("菜单信息","UTF-8");
            response.setHeader("Content-Disposition","attachment;filename*=UTF-8''"+filename+".xls");
            EasyExcel.write(response.getOutputStream(), Menu.class).sheet("菜单信息").doWrite(menuService.list());
        } catch (IOException e) {
            log.error("下载Excel文件失败");
            e.printStackTrace();
        }
    }

    @PostMapping("/downloadRoleExcel")
    @ApiOperation(value = "角色信息Excel",notes = "下载角色Excel")
    @ResponseBody
    public void getRoleExcel(HttpServletResponse response)  {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String filename= URLEncoder.encode("角色信息","UTF-8");
            response.setHeader("Content-Disposition","attachment;filename*=UTF-8''"+filename+".xls");
            EasyExcel.write(response.getOutputStream(), Role.class).sheet("角色信息").doWrite(roleService.list());
        } catch (IOException e) {
            log.error("下载Excel文件失败");
            e.printStackTrace();
        }
    }
    @PostMapping("/downloadDeptExcel")
    @ApiOperation(value = "部门信息Excel",notes = "下载部门Excel")
    @ResponseBody
    public void getDeptExcel(HttpServletResponse response)  {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String filename= URLEncoder.encode("部门信息","UTF-8");
            response.setHeader("Content-Disposition","attachment;filename*=UTF-8''"+filename+".xls");
            EasyExcel.write(response.getOutputStream(), Department.class).sheet("员工信息").doWrite(departmentService.list());
        } catch (IOException e) {
            log.error("下载Excel文件失败");
            e.printStackTrace();
        }
    }

    @PostMapping("/downloadInStockExcel")
    @ApiOperation(value = "部门信息Excel",notes = "下载部门Excel")
    @ResponseBody
    public void getInStockExcel(HttpServletResponse response)  {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String filename= URLEncoder.encode("入库信息","UTF-8");
            response.setHeader("Content-Disposition","attachment;filename*=UTF-8''"+filename+".xls");
            EasyExcel.write(response.getOutputStream(), InStock.class).sheet("员工信息").doWrite(inStockService.list());
        } catch (IOException e) {
            log.error("下载Excel文件失败");
            e.printStackTrace();
        }
    }
}
